﻿using AutoMapper;
using Microsoft.AspNetCore.Components.Forms.Mapping;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using TrackSystem.Contracts;
using TrackSystem.Entities.Dtos.Sensor;
using TrackSystem.Entities.Extensions;
using TrackSystem.Entities.Models;
using TrackSystem.Entities.RequestFeatures;
using TrackSystem.EntityFramework.Repositories.Extensions;

namespace TrackSystem.EntityFramework.Repositories
{
    public class SensorRepository : Repositories<SensorTable, int>, ISensorRepository
    {
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContent"></param>
        /// <param name="mapper"></param>
        public SensorRepository(TkDBContent dbContent, IMapper mapper) : base(dbContent)
        {
            this._mapper = mapper;
        }

        /// <summary>
        /// 获取所有成员
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<SensorTable>> GetAllWithChannelAsync()
        {
            return await _dbContext.Sensors
                .Include(a => a.Channel)
                .Include(b => b.Equip)
                .OrderBy(a => a.channelID)
                .ThenBy(a => a.Station)
                .ThenBy(a => a.Name).ToArrayAsync();
        }

        public async Task<ApiResult<SensorWithChannelDto>> GetSingleWithChannelAsync(int id)
        {
            var sensor = await _dbContext.Sensors
                .Include(a => a.Channel)
                .Include(b => b.Equip)
                .FirstOrDefaultAsync(x => x.Id == id);
            return sensor == null ? 
                ApiResult<SensorWithChannelDto>.Fail($"传感器ID {id} 不存在", StatusCodes.Status404NotFound) : 
                ApiResult<SensorWithChannelDto>.Ok(_mapper.Map<SensorWithChannelDto>(sensor), "获取传感器成功");
        }


        /// <summary>
        /// 以分页方式获取传感器列表
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public PagedList<SensorTable> GetPagedSensors(RequestParameter parameter)
        {
            return  Table.OrderByQuery(parameter.QueryString)
                .ToPagedList(parameter.PageNumber, parameter.PageSize);
        }

        /// <summary>
        /// 添加传感器
        /// </summary>
        /// <param name="sensor"></param>
        /// <returns></returns>
        public async Task<ApiResult<SensorWithChannelDto>> AddSensorAsync(SensorTable sensor)
        {
            try
            {
                // 检查传感器名称是否已存在
                var count = await Table.CountAsync(x => x.Name == sensor.Name.Trim());
                if (count > 0)
                {
                    return ApiResult<SensorWithChannelDto>.Fail($"传感器名称 {sensor.Name} 已存在", StatusCodes.Status400BadRequest);
                }

                // 检查通道是否存在
                var channel = await _dbContext.Channels.FirstOrDefaultAsync(x => x.Id == sensor.channelID);
                if (channel == null)
                {
                    return ApiResult<SensorWithChannelDto>.Fail($"通道ID {sensor.channelID} 不存在", StatusCodes.Status400BadRequest);
                }

                if (ProtocolDefine.Params.TryGetValue(channel.Protocol, out var protocolParams))
                {
                    sensor.RO_Address = protocolParams.StartAdr_RO != -1? protocolParams.StartAdr_RO : sensor.RO_Address;
                    sensor.RO_Length = protocolParams.RegLen_RO != -1? protocolParams.RegLen_RO : sensor.RO_Length;
                    sensor.RW_Address = protocolParams.StartAdr_RW != -1 ? protocolParams.StartAdr_RW : sensor.RW_Address;
                    sensor.RW_Length = protocolParams.RegLen_RW != -1 ? protocolParams.RegLen_RW : sensor.RW_Length;
                }

                // 检查同一通道下相同站号的传感器数量
                if (protocolParams != null && !protocolParams.ExclusiveMode)  // 独占模式下检查站号
                {
                    count = await _dbContext.Sensors.CountAsync(x => x.channelID == sensor.channelID && x.Station == sensor.Station);
                    if (count > 0)
                    {
                        return ApiResult<SensorWithChannelDto>.Fail($"通道{channel.Name}  下站号 {sensor.Station} 的传感器已存在", StatusCodes.Status400BadRequest);
                    }
                }
                if (protocolParams != null && protocolParams.ExclusiveMode)  // 非独占模式下检查站号和通道ID组合
                {
                    count = await _dbContext.Sensors.CountAsync(x => x.channelID == sensor.channelID);
                    if (count > 0)
                    {
                        return ApiResult<SensorWithChannelDto>.Fail($"通道{channel.Name} 下已经有传感器已存在", StatusCodes.Status400BadRequest);
                    }
                }


                var result = await InsertAsync(sensor);
                return ApiResult<SensorWithChannelDto>.Ok(_mapper.Map<SensorWithChannelDto>(result), "传感器添加成功");

            }
            catch (Exception ex)
            {
                return ApiResult<SensorWithChannelDto>.Fail(ex.Message, StatusCodes.Status500InternalServerError);
            }
        }

        /// <summary>
        /// 更新传感器
        /// </summary>
        /// <param name="sensor"></param>
        /// <returns></returns>
        public async Task<ApiResult<SensorWithChannelDto>> UpdateSensorAsync(SensorTable sensor)
        {
            try
            {
                var count = await Table.CountAsync(x => x.Id == sensor.Id);
                if (count == 0)
                {
                    return await Task.FromResult(ApiResult<SensorWithChannelDto>.Fail($"传感器ID {sensor.Id} 不存在", StatusCodes.Status404NotFound));
                }

                count = await Table.CountAsync(x => x.Name == sensor.Name.Trim() && x.Id != sensor.Id);
                if (count > 0)
                {
                    return await Task.FromResult(ApiResult<SensorWithChannelDto>.Fail($"传感器名称 {sensor.Name} 已存在", StatusCodes.Status400BadRequest));
                }

                var channel = await _dbContext.Channels.FirstOrDefaultAsync(x => x.Id == sensor.channelID);
                if (channel == null)
                {
                    return await Task.FromResult(ApiResult<SensorWithChannelDto>.Fail($"通道ID {sensor.channelID} 不存在", StatusCodes.Status400BadRequest));
                }
                if (ProtocolDefine.Params.TryGetValue(channel.Protocol, out var protocolParams))
                {
                    sensor.RO_Address = protocolParams.StartAdr_RO != -1 ? protocolParams.StartAdr_RO : sensor.RO_Address;
                    sensor.RO_Length = protocolParams.RegLen_RO != -1 ? protocolParams.RegLen_RO : sensor.RO_Length;
                    sensor.RW_Address = protocolParams.StartAdr_RW != -1 ? protocolParams.StartAdr_RW : sensor.RW_Address;
                    sensor.RW_Length = protocolParams.RegLen_RW != -1 ? protocolParams.RegLen_RW : sensor.RW_Length;
                }

                // 检查同一通道下相同站号的传感器数量
                if (protocolParams != null && !protocolParams.ExclusiveMode)  // 独占模式下检查站号
                {
                     count = await _dbContext.Sensors.CountAsync(x => x.channelID == sensor.channelID && x.Station == sensor.Station && x.Id != sensor.Id);
                    if (count > 0)
                    {
                        return ApiResult<SensorWithChannelDto>.Fail($"通道{channel.Name} 下站号 {sensor.Station} 的传感器已存在", StatusCodes.Status400BadRequest);
                    }
                }
                if (protocolParams != null && protocolParams.ExclusiveMode)  // 非独占模式下检查站号和通道ID组合
                {
                    count = await _dbContext.Sensors.CountAsync(x => x.channelID == sensor.channelID && x.Id != sensor.Id);
                    if (count > 0)
                    {
                        return ApiResult<SensorWithChannelDto>.Fail($"通道{channel.Name} 下已经有传感器已存在", StatusCodes.Status400BadRequest);
                    }
                }


                var result = await UpdateAsync(sensor);
                return ApiResult<SensorWithChannelDto>.Ok(_mapper.Map<SensorWithChannelDto>(result), "传感器修改成功");

            }
            catch (Exception ex)
            {
                return ApiResult<SensorWithChannelDto>.Fail(ex.Message, StatusCodes.Status500InternalServerError);
            }
        }

        /// <summary>
        /// 删除传感器
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<ApiResult<SensorWithChannelDto>> DeleteSensorAsync(int Id)
        {
            try
            {
                var sensor = await Table.FirstOrDefaultAsync(x => x.Id == Id);
                if (sensor == null)
                {
                    return ApiResult<SensorWithChannelDto>.Fail($"传感器ID {Id} 不存在", StatusCodes.Status404NotFound);
                }

                await DeleteAsync(sensor);
                return ApiResult<SensorWithChannelDto>.Ok(_mapper.Map<SensorWithChannelDto>(sensor), "传感器删除成功");
            }
            catch (Exception ex)
            {
                return ApiResult< SensorWithChannelDto>.Fail(ex.Message, StatusCodes.Status500InternalServerError);
            }
        }

    }
}
